<!-- 用户管理模式2 -->
<template>
  <div class="app-container flex-row">
    <div class="conmmon-container-left scroll__y__content scrollbar-no-width" style="width:280px">
      <organization-tree v-model="listQuery.orgId" :show-options="true" @selectedOrg="selectedOrg" />
    </div>
    <div class="conmmon-container-main flex-main">
      <template v-if="currentSelectedOrg.id">
        <!--搜索条件-->
        <div class="filter-container">
          <el-form :model="listQuery" :inline="true">
            <el-form-item>
              <el-input v-model="listQuery.keyword" placeholder="请输入真实姓名、手机号、用户名、职务" class="filter-item" style="width:300px" @keyup.enter.native="handleFilter" />
            </el-form-item>
            <el-form-item>
              <el-button plain type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
              <el-button plain icon="el-icon-refresh" @click="handleReset">重置</el-button>

            </el-form-item>
          </el-form>
        </div>
        <!--列表-->
        <div class="table-container flex-main">
          <div class="table-container-header">
            <table-toolbar @create="handleCreate" @refresh="handleFilter" @remove="removeRecord">
              <template slot="rightTool">
                <el-checkbox v-model="listQuery.includeChildren" style="line-height: 33px;">是否包含下级部门</el-checkbox>
              </template>
            </table-toolbar>
          </div>
          <el-table
            ref="multipleTable"
            :data="list"
            header-cell-class-name="table-header"
            fit
            height="100%"
            highlight-current-row
            @selection-change="handleSelectionChange"
            @sort-change="sortChange">
            <el-table-column :selectable="selectable" type="selection" width="50" align="center" />
            <el-table-column align="center" prop="id" width="60" label="#">
              <template slot-scope="scope">{{ scope.$index+1 }}</template>
            </el-table-column>
            <el-table-column :show-overflow-tooltip="true" label="头像" prop="avatar" width="70" align="center">
              <template slot-scope="scope">
                <img :src="global.getFileView(scope.row.avatar)" class="common-round-image-32" :title="scope.row.realName" @error="handleImageError">
              </template>
            </el-table-column>
            <el-table-column :show-overflow-tooltip="true" label="用户名" prop="userName" width="100">
              <template slot-scope="scope">
                <span class="color-primary common-cursor" @click="handleLookDetails(scope.row)">{{ scope.row.userName }}</span>
              </template>
            </el-table-column>
            <el-table-column :show-overflow-tooltip="true" label="员工号" width="100" prop="userCode" />
            <el-table-column :show-overflow-tooltip="true" label="姓名" prop="realName" width="100" />
            <el-table-column label="性别" prop="gender" width="80" align="center">
              <template slot-scope="scope">{{ scope.row.gender==1 ?'男': scope.row.gender==2 ? '女' : '保密' }}</template>
            </el-table-column>
            <el-table-column :show-overflow-tooltip="true" label="手机" prop="mobile" width="110" />
            <el-table-column :show-overflow-tooltip="true" label="座机" prop="phone" width="150">
              <template slot-scope="scope">
                <span><el-tag type="primary" effect="plain" size="mini" style="margin-right: 5px;">个人</el-tag>{{ scope.row.phone?scope.row.phone:'-' }}</span><br>
                <span><el-tag type="success" effect="plain" size="mini" style="margin-right: 5px;">办公</el-tag>{{ scope.row.orgPhone?scope.row.orgPhone:'-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="职务" prop="orgJob" width="200" :show-overflow-tooltip="true">
              <template slot-scope="scope">{{ scope.row.orgJob?(scope.row.orgJob.split(":")[1]):'' }}</template>
            </el-table-column>
            <el-table-column :show-overflow-tooltip="true" label="邮箱" prop="email" width="150" />
            <el-table-column :show-overflow-tooltip="true" label="所属部门" width="140">
              <template slot-scope="scope">
                <el-tag effect="plain">{{ scope.row.organizationName }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="加入部门" min-width="260" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-tag v-for="item in scope.row.upmsOrganizations" :key="item.id" effect="plain" style="margin-right:5px">{{ item.organizationName }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column :show-overflow-tooltip="true" label="直属领导" prop="reportsTo" width="100">
              <template slot-scope="scope">
                <span v-if="scope.row.reportsTo" class="color-primary">{{ scope.row.reportsTo.split(":")[1] }}</span>
                <span v-else class="color-danger">暂无领导</span>
              </template>
            </el-table-column>
            <el-table-column prop="addTime" width="150" sortable label="加入时间">
              <template slot-scope="scope">{{ scope.row.addTime | formatDate }}</template>
            </el-table-column>
            <el-table-column prop="gmtCreated" width="150" sortable label="录入时间">
              <template slot-scope="scope">{{ scope.row.gmtCreated | formatDate }}</template>
            </el-table-column>
            <el-table-column label="操作" align="center" fixed="right" width="90">
              <template slot-scope="scope">
                <div v-if="currentUserInfo.id==scope.row.id">
                  <el-tag>当前</el-tag>
                </div>
                <div v-if="currentUserInfo.id!=scope.row.id">
                  <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
                  <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination_handler">
          <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
        </div>
      </template>
      <el-empty v-if="!currentSelectedOrg.id" :description="'该分类下暂未添加任何组织机构'">
        赶快联系管理员去新增吧！
      </el-empty>
    </div>

    <!--新增/编辑侧边栏-->
    <side-box :show="sideBox.recordShow" width="700px" :title="sideBox.title" @close="sideBox.recordShow=!sideBox.recordShow">
      <template slot="body">
        <el-form ref="dataForm" :rules="recordRules" :model="userRecord" label-position="right" label-width="120px">
          <div class="common-title m-b-20"><h2 class="bold">基本信息</h2></div>
          <el-row>
            <el-col :span="12">
              <el-form-item label="手机:" prop="mobile">
                <el-input v-model="userRecord.mobile" maxlength="11" show-word-limit placeholder="请输入手机号码" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="姓名:" prop="realName">
                <el-input v-model="userRecord.realName" :disabled="sideBox.status!=='create'" maxlength="10" show-word-limit placeholder="请输入姓名" />
              </el-form-item>

            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="账号:" prop="userName">
                <el-input v-model="userRecord.userName" :disabled="sideBox.status!=='create'" maxlength="11" show-word-limit placeholder="请输入账号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别:" prop="gender">
                <el-radio-group v-model="userRecord.gender">
                  <el-radio :label="1">男</el-radio>
                  <el-radio :label="2">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="电话:" prop="phone">
                <el-input v-model="userRecord.phone" show-word-limit placeholder="请输入电话" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱:" prop="email">
                <email-input-select v-model="userRecord.email" placeholder="请输入电子邮箱" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="用户类别:" prop="category">
                <data-dict-select v-model="userRecord.category" :code="'userCategory'" placeholder="请选择用户类别" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="直属领导:" prop="reportsTo">
                <UserSelector v-model="userRecord.reportsTo" mode="input" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注:" prop="projectDesc">
                <el-input v-model="userRecord.remarks" :rows="4" type="textarea" maxlength="200" show-word-limit placeholder="请输入备注" />
              </el-form-item>
            </el-col>
          </el-row>

          <div class="common-title m-b-20"><h2 class="bold">员工信息</h2></div>
          <el-row>
            <el-col :span="12">
              <el-form-item label="内部员工:" prop="isInner">
                <el-radio-group v-model="userRecord.isInner">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="通讯录:" prop="isAddMailList">
                <el-radio-group v-model="userRecord.isAddMailList">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="员工编号:" prop="userCode">
                <el-input v-model="userRecord.userCode" :disabled="sideBox.status!=='create'" maxlength="7" show-word-limit placeholder="请输入员工编号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="授权码:" prop="authorizationCode">
                <el-input v-model="userRecord.authorizationCode" maxlength="8" show-word-limit placeholder="请输入授权码" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="归属部门:">
                <el-input v-model="userRecord.orgFullName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="岗位:" prop="userOrganizationDto.job">
                <el-select v-model="userRecord.userOrganizationDto.job" filterable placeholder="请选择岗位" style="width:100%">
                  <el-option
                    v-for="item in posts"
                    :key="item.value"
                    :label="item.name+'('+item.code+')'"
                    :value="item.code+':'+item.name">
                    <span style="float: left">{{ item.name }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.code }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="电话:" prop="userOrganizationDto.phone">
                <el-input v-model="userRecord.userOrganizationDto.phone" show-word-limit placeholder="请输入电话" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排序:" prop="userOrganizationDto.orders">
                <el-input-number v-model="userRecord.userOrganizationDto.orders" placeholder="请输入排序" show-word-limit :min="1" :max="9999" style="width:100%" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="角色" prop="userRole">
            <div v-for="group in roleList" :key="group.id">
              <el-checkbox
                :label="group.name"
                disabled>
                {{ group.name }}
              </el-checkbox>
              <el-checkbox-group v-model="userRecord.userRole">
                <el-checkbox
                  v-for="item in group.children"
                  :key="item.id"
                  :label="item.id"
                  :value="item.id">{{ item.name }}</el-checkbox>
              </el-checkbox-group>
            </div>
            <el-empty v-if="roleList.length===0" description="暂无可用角色" />

          </el-form-item>
        </el-form>
      </template>
      <template slot="foot">
        <el-button type="primary" @click="sideBox.status==='create'?createData():updateData()">确定</el-button>
      </template>
    </side-box>
    <user-details ref="userDetails" />
  </div>
</template>

<script>

export default {
  components: { },
  data() {
    var checkUsertName = (rule, value, callback) => {
      this.$store.dispatch('userValidateExistByField', { id: this.userRecord.id, field: 'userName', value: value }).then(response => {
        if (response) {
          return callback(new Error('用户名已存在，请重新输入'))
        } else {
          return callback()
        }
      }).catch((_) => { })
    }
    var checkUsertMobile = (rule, value, callback) => {
      this.$store.dispatch('getUserByMobile', value).then(res => {
        if (res) {
          this.userRecord = {
            ...this.userRecord,
            ...res,
            organizationIds: this.currentSelectedOrg.fullPathId,
            organizationId: this.currentSelectedOrg.id
          }
          this.sideBox.status = 'update'
        } else {
          this.sideBox.status = 'create'
        }
        return callback()
      }).catch((_) => {
        return callback()
      })
    }
    return {
      currentSelectedOrg: {},
      currentUserInfo: this.$store.getters.userInfo,
      userId: '',
      list: null,
      listLoading: true,
      total: 0,
      listQuery: {
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        sort: this.common.SORT_DEFAULT,
        orgId: '',
        keyword: '',
        includeChildren: true,
        includeOrgs: 1
      },
      multipleSelectionRecords: [],
      roleList: [],
      posts: [],
      // 固定写法
      sideBox: {
        recordShow: false,
        title: '',
        status: 'create' // 对话框状态
      },
      userRecord: {
        userRole: [],
        userOrganizationDto: {}
      },
      recordRules: {
        userName: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { required: true, validator: checkUsertName, trigger: 'blur' }
        ],
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
          { validator: this.commonValidate.validateRealName, trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择用户类别', trigger: 'blur' }
        ],
        email: [
          { validator: this.commonValidate.validateEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: this.commonValidate.validateMobile, trigger: 'blur' },
          { required: true, validator: checkUsertMobile, trigger: 'blur' }
        ],
        userCode: [
          { min: 7, max: 7, message: '必须是7个数字', trigger: 'blur' },
          { validator: this.commonValidate.validateNumber, trigger: 'blur' }
        ],

        'userOrganizationDto.job': [
          { required: true, message: '请选择岗位', trigger: 'blur' }
        ],
        'userOrganizationDto.orders': [
          { required: true, message: '请输入员工排序', trigger: 'blur' }
        ],

        isInner: [
          { required: true, message: '请选择是否内部员工', trigger: 'blur' }
        ],
        isAddMailList: [
          { required: true, message: '请选择是否添加至通讯录', trigger: 'blur' }
        ],
        idNumber: [
          { validator: this.commonValidate.validateIDCard, trigger: 'blur' }
        ]
      },

      adjustmentOrgRecord: {}
    }
  },
  computed: {

  },
  watch: {
    'listQuery.orgId'(val) {
      if (val) {
        this.listQuery.page = 1
        this.fetchData()
      }
    },
    'listQuery.includeChildren'(val) {
      this.listQuery.page = 1
      this.fetchData()
    }
  },
  created() {

  },
  methods: {

    handleUserInfoTabClick() {

    },
    selectedOrg(val) {
      this.currentSelectedOrg = val
      this.listQuery = {
        ...this.listQuery,
        orgId: this.currentSelectedOrg.id,
        keyword: ''
      }
    },
    /**
     * 全选/反选
     */
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    selectable(row) {
      if (row.id !== this.currentUserInfo.id) {
        return true
      } else {
        return false
      }
    },

    async fetchData() {
      this.listLoading = true
      const response = await this.$store.dispatch('upmsUserPageByOrgId', {
        ...this.listQuery,
        includeChildren: this.listQuery.includeChildren ? 1 : 2
      })
      this.listLoading = false
      this.list = response.records
      this.list.filter((item) => {
        item.isLocked = !item.isLocked
        return true
      })
      this.total = response.total
    },
    // 固定写法
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = this.common.SORT_DEFAULT
      }
      this.handleFilter()
    },
    // 固定写法
    handleCommand(val) {
    },
    /**
     * 搜索
     */
    handleFilter() {
      this.listQuery = {
        ...this.listQuery,
        page: 1
      }
      this.fetchData()
    },
    /**
     * 重置
     */
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        sort: this.common.SORT_DEFAULT,
        keyword: '',
        includeChildren: 1
      }
      this.fetchData()
    },
    /* 新增*/
    handleCreate() {
      this.roleTree()
      this.fetchPostList()
      this.userRecord = {
        userCode: this.T.randomNumber(7),
        authorizationCode: this.T.randomNumber(8),
        gender: 1,
        isInner: 1,
        isAddMailList: 1,
        category: '1:默认分类',
        userRole: [],
        userOrganizationDto: {
          orders: 1,
          type: this.currentSelectedOrg.type,
          organizationId: this.currentSelectedOrg.id,
          fullOrganizationId: this.currentSelectedOrg.fullPathId
        },
        orgFullName: this.currentSelectedOrg.fullPathName

      }
      this.sideBox.status = 'create'
      this.sideBox.recordShow = true
      this.sideBox.title = '新增用户'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      const temp = Object.assign({}, this.userRecord)
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          temp.role = temp.userRole.join(',')
          delete temp.userRole
          this.$store.dispatch('userSave', temp).then(response => {
            this.sideBox.recordShow = false
            this.msgSuccess('创建成功')
            this.handleReset()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },
    async handleLookDetails(row) {
      this.$refs.userDetails.init(row.id)
    },
    /* 编辑*/
    async handleUpdate(row) {
      this.roleTree()
      this.fetchPostList()
      this.formEcho(row.userOrgId)
      this.sideBox.status = 'update'
      this.sideBox.recordShow = true
      this.sideBox.title = '编辑用户[' + row.userName + ']'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      const tempData = Object.assign({}, this.userRecord)

      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          tempData.role = tempData.userRole.join(',')
          delete tempData.userRole

          this.$store.dispatch('userUpdate', tempData).then(response => {
            this.sideBox.recordShow = false
            this.msgSuccess('修改成功')
            this.handleFilter()
          })
            .catch(() => {
              this.sideBox.recordShow = true
            })
        }
      })
    },
    async formEcho(id) {
      const res = await this.$store.dispatch('getUserByUserOrgId', id)
      this.userRecord = {
        ...res,
        orgFullName: res.organizationName,
        userRole: [],
        userOrganizationDto: {
          orders: res.orders,
          type: res.orgType,
          organizationId: res.organizationId,
          fullOrganizationId: res.fullOrganizationId,
          phone: res.orgPhone,
          job: res.orgJob
        }
      }
      if (this.userRecord.reportsTo) {
        if (this.userRecord.reportsTo.split(':').length === 2) {
          this.userRecord.reportsToName = this.userRecord.reportsTo.split(':')[1]
          this.userRecord.reportsToId = this.userRecord.reportsTo.split(':')[0]
        }
      }
      if (res.upmsRoles.length > 0) {
        var userRoles = []
        res.upmsRoles.forEach((item) => {
          userRoles.push(item.id)
        })
        this.userRecord = {
          ...this.userRecord,
          userRole: userRoles
        }
      }
    },

    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        let isDelted = true
        const ids = []
        this.multipleSelectionRecords.forEach((v, i) => {
          if (this.$store.getters.userInfo.id === v.id) {
            this.msgWarning('自己不能删除当前用户')
            isDelted = false
          }
          ids.push(v.userOrgId)
        })
        if (isDelted) {
          this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$store.dispatch('organizationUserRemove', ids).then(response => {
              this.handleReset()
              this.msgSuccess('删除成功')
            }).catch(() => { })
          }).catch(() => { })
        }
      } else {
        this.msgWarning('请选择要删除的记录')
      }
    },

    roleTree() {
      this.$store.dispatch('roleTreeTable', {}).then((res) => {
        this.roleList = res
      }).catch((_) => {})
    },
    // 获取岗位
    fetchPostList() {
      this.$store.dispatch('postList').then((res) => {
        this.posts = res
      }).catch((_) => {
      })
    }

  }
}
</script>
<style lang="scss" scoped>
</style>

